/**
 * Created by Alexander Malapheev.
 * User: amalafe
 * Date: 7/27/11
 * Time: 12:35 PM
 */

Namespace("sketch.framework");

(function(fwk) {
    var resourceTotalCount = 0;
    var resourceCompletedCount = 0;

    fwk.Resources = {
        completed:function(){
        },
        reportProgress:function(event){
        }
    };

    var startLoading = function(){
        resourceTotalCount++;
    };

    var completeLoading = function(){
        resourceCompletedCount ++;
        fwk.Resources.reportProgress({loaded:resourceCompletedCount, count:resourceTotalCount});
        if(resourceCompletedCount === resourceTotalCount){
            fwk.Resources.completed();
        }
    };

    fwk.Resources.loadImage = function(/*string*/resourceName, /*URI*/url) {
        var img = document.createElement('img');
        startLoading();
        img.onload = function() {
            fwk.Resources[resourceName] = img;
            completeLoading();
        };
        img.src = url;
    };

    fwk.Resources.loadGradientFromImage = function(/*string*/resourceName, /*URI*/url) {
        var img = document.createElement('img');
        startLoading();
        img.onload = function() {
            var canvas = document.createElement("canvas");
            context = canvas.getContext('2d');
            var w = img.width;
            var h = img.height;
            canvas.width = w;
            canvas.height = h;
            context.drawImage(img, 0, 0);
            var data = null;
            try {
                try {
                    data = context.getImageData(0, 0, w, h);
                }
                catch (e) {
                    netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
                    data = context.getImageData(0, 0, w, h);
                }
            } catch (e) {
                throw new Error("unable to access image data: " + e)
            }

            if (w < h) {
                var grayScale = [];
                for(var i = 0; i< h*4; i+=4){
                    // grayColor = (0.21R + 0.71.G + 0.07B) * alpha
                    grayScale[i/4] = ~~(0.25 * data.data[i+0] + 0.25 * data.data[i+1] + 0.25 * data.data[i+2] + 0.25*data.data[i+3]);
                }

                var diff = [];
                diff[0] = grayScale[0];
                diff[h-1] = grayScale[h-1];
                for(i = 1; i < h-1; ++i){
                    diff[i] = grayScale[i]-grayScale[i-1];
                }

                var gradient = [];
                for(i = 0; i < h; ++i){
                    if(Math.abs(diff[i])>1){
                        var r = data.data[i*4+0],
                            g = data.data[i*4+1],
                            b = data.data[i*4+2],
                            a = data.data[i*4+3]/255;
                        gradient.push({
                            offset:i/h,
                            color:'rgba('+r+','+g+','+b+','+a+ ')'
                        });
                    }
                }

                gradient.toBrush = function(context, x1, y1, x2, y2){
                    var lingrad = context.createLinearGradient(x1, y1, x2, y2);
                    for(var i = 0, length = gradient.length; i < length; ++i){
                        lingrad.addColorStop(gradient[i].offset, gradient[i].color);
                    }

                    return lingrad;
                };

                fwk.Resources[resourceName] = gradient;
                completeLoading();//TODO: catch when was error during loading
            }
        };
        img.src = url;

    };
})(sketch.framework);
